<template>
  <div class="container">
    <div class="container_titleBox">
      <h3 class="container_title">{{ $t('entity.add_title') }}</h3>
      <el-icon class="close" @click="iconClosePage"><CloseBold /></el-icon>
    </div>

    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      inline
      label-position="top"
      require-asterisk-position="right"
    >
      <!-- 实体基础信息 -->
      <div class="basic">
        <!-- 实体类型 -->
        <el-form-item class="common" :label="$t('entity.add_basic_identity')" prop="identity">
          <el-radio-group v-model="identity" :disabled="onlyRead">
            <el-radio :label="1" border>{{ $t('entity.add_basic_identity_legal') }}</el-radio>
            <el-radio :label="2" border>{{ $t('entity.add_basic_identity_physics') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 所属国家 -->
        <el-form-item class="common" :label="$t('entity.add_basic_nationality')" prop="nationality">
          <el-radio-group v-model="nationality" :disabled="onlyRead">
            <el-radio :label="1" border>{{ $t('entity.add_basic_nationality_brazilian') }}</el-radio>
            <el-radio :label="2" border>{{ $t('entity.add_basic_nationality_foreign') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <!-- 实体一般信息 -->
      <div v-if="nowType" class="general">
        <h5 class="general_title">
          {{ $t('entity.add_general') }}
        </h5>
        <div class="general_content">
          <!-- 实体类型 -->
          <el-form-item
            :label="$t('entity.add_general_entityType')"
            prop="entityType"
            class="common"
            :required="required"
          >
            <el-select
              v-model="ruleForm.entityType"
              :placeholder="$t('entity.add_general_entityType')"
              :style="{ width: '100%' }"
              :disabled="onlyRead"
            >
              <el-option
                v-for="item in entityTypeOptions"
                :key="item.value"
                :label="$t(item.label)"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <!-- 实体名称 -->
          <el-form-item
            :label="$t('entity.add_general_entityName')"
            prop="entityName"
            class="common"
            :required="required"
          >
            <el-input v-model="ruleForm.entityName" autosize type="textarea" :disabled="onlyRead" />
          </el-form-item>
          <!-- 文件 -->
          <el-form-item
            :label="$t('entity.add_general_document')"
            prop="document"
            class="common document"
            :required="required"
          >
            <el-select
              v-model="ruleForm.documentType"
              :placeholder="$t('entity.add_general_documentType')"
              :style="{ width: '160px', marginRight: '10px' }"
              :disabled="onlyRead"
            >
              <el-option
                v-for="item in documentTypeOptions"
                :key="item.value"
                :label="$t(item.label)"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
            <el-input
              v-model="ruleForm.documentNumber"
              class="input-with-select"
              autosize
              type="textarea"
              resize="none"
              :disabled="onlyRead"
            />
          </el-form-item>
          <!-- 交易名称 -->
          <el-form-item
            v-if="nowType === 'LB' || nowType === 'LF'"
            :label="$t('entity.add_general_socialReason')"
            prop="tradeName"
          >
            <el-input v-model="ruleForm.tradeName" autosize type="textarea" resize="none" :disabled="onlyRead" />
          </el-form-item>
          <!-- 州登记 -->
          <el-form-item
            v-if="nowType === 'LB' || nowType === 'LF'"
            :label="$t('entity.add_general_stateRegistration')"
            prop="stateRegistration"
          >
            <el-input
              v-model="ruleForm.stateRegistration"
              autosize
              type="textarea"
              resize="none"
              :disabled="onlyRead"
            />
          </el-form-item>
          <!-- 城市登记 -->
          <el-form-item
            v-if="nowType === 'LB' || nowType === 'LF'"
            :label="$t('entity.add_general_municipalRegistration')"
            prop="cityRegistration"
          >
            <el-input v-model="ruleForm.cityRegistration" autosize type="textarea" resize="none" :disabled="onlyRead" />
          </el-form-item>
          <!-- 职业 -->
          <el-form-item
            v-if="nowType === 'PB' || nowType === 'PF'"
            :label="$t('entity.add_general_profession')"
            prop="profession"
          >
            <el-input v-model="ruleForm.profession" autosize type="textarea" resize="none" :disabled="onlyRead" />
          </el-form-item>
          <!-- OAB -->
          <el-form-item
            v-if="nowType === 'PB' && isLawyer"
            :label="$t('entity.add_general_oab')"
            prop="attorneyRegistrationNumber"
          >
            <el-input
              v-model="ruleForm.attorneyRegistrationNumber"
              autosize
              type="textarea"
              resize="none"
              :disabled="onlyRead || !isLawyer"
            />
          </el-form-item>
          <!-- RG -->
          <el-form-item v-if="nowType === 'PB'" :label="$t('entity.add_general_rg')" prop="idCard">
            <el-input v-model="ruleForm.idCard" autosize type="textarea" resize="none" :disabled="onlyRead" />
          </el-form-item>
          <!-- 婚姻状况 -->
          <el-form-item
            v-if="nowType === 'PB' || nowType === 'PF'"
            :label="$t('entity.add_general_civilStatus')"
            prop="civilStatus"
          >
            <el-select
              v-model="ruleForm.civilStatus"
              :placeholder="$t('entity.add_general_civilStatus')"
              :style="{ width: '100%' }"
              :disabled="onlyRead"
            >
              <el-option
                v-for="item in civilStatusOptions"
                :key="item.value"
                :label="$t(item.label)"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
        </div>
      </div>
      <!-- 实体地址信息 -->
      <div v-if="nowType" class="address">
        <h5 class="address_title">
          {{ $t('entity.add_address') }}
        </h5>
        <div class="address_content">
          <!-- 邮编 -->
          <el-form-item :label="$t('entity.add_address_cep')" prop="zipCode" class="common" :required="required">
            <el-input v-model="ruleForm.zipCode" autosize type="textarea" resize="none" :disabled="onlyRead" />
          </el-form-item>
          <!-- 街号 -->
          <el-form-item
            :label="$t('entity.add_address_number')"
            prop="streetNumber"
            class="common"
            :required="required"
          >
            <el-input v-model="ruleForm.streetNumber" autosize type="textarea" resize="none" :disabled="onlyRead" />
          </el-form-item>
          <!-- 地址 -->
          <el-form-item :label="$t('entity.add_address_address')" prop="address" class="common" :required="required">
            <el-input
              v-model="ruleForm.address"
              :disabled="ruleForm.isBaxiCep || onlyRead"
              autosize
              type="textarea"
              resize="none"
            />
          </el-form-item>
          <!-- 地区 -->
          <el-form-item :label="$t('entity.add_address_district')" prop="district" class="common" :required="required">
            <el-input
              v-model="ruleForm.district"
              :disabled="ruleForm.isBaxiCep || onlyRead"
              autosize
              type="textarea"
              resize="none"
            />
          </el-form-item>
          <!-- 国家省市 -->
          <el-form-item
            :label="
              $t('entity.add_address_country') +
              '/' +
              $t('entity.add_address_state') +
              '/' +
              $t('entity.add_address_city')
            "
            prop="countryStateCity"
            class="common csc"
            :required="required"
          >
            <el-select
              v-model="ruleForm.country"
              filterable
              :placeholder="$t('entity.add_address_country')"
              :disabled="ruleForm.isBaxiCep || onlyRead"
            >
              <el-option v-for="item in countryOptions" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
            <el-select
              v-model="ruleForm.state"
              filterable
              :placeholder="$t('entity.add_address_state')"
              :disabled="!ruleForm.country || ruleForm.isBaxiCep || onlyRead"
            >
              <el-option v-for="item in stateOptions" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
            <el-select
              v-model="ruleForm.city"
              filterable
              :placeholder="$t('entity.add_address_city')"
              :disabled="!ruleForm.state || ruleForm.isBaxiCep || onlyRead"
            >
              <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
        </div>
      </div>
      <!-- 实体联系信息 -->
      <div v-if="nowType" class="contact">
        <h5 class="contact_title">
          {{ $t('entity.add_contact') }}
        </h5>
        <div class="contact_content">
          <!-- 姓名 -->
          <el-form-item :label="$t('entity.add_contact_name')" prop="name">
            <el-input v-model="ruleForm.name" autosize type="textarea" resize="none" :disabled="onlyRead" />
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item :label="$t('entity.add_contact_email')" prop="email">
            <el-input v-model="ruleForm.email" autosize type="textarea" resize="none" :disabled="onlyRead" />
          </el-form-item>
          <!-- 手机号1 -->
          <el-form-item :label="$t('entity.add_contact_phoneNumber1')" prop="phoneNumber" class="phoneNumber1">
            <el-select
              v-model="ruleForm.phoneAreaCode1"
              filterable
              :placeholder="$t('entity.add_contact_phoneNumber_areacode')"
              :style="{ width: '160px', marginRight: '10px' }"
              :disabled="onlyRead"
            >
              <el-option
                v-for="item in areaCodeOptions.value"
                :key="item.id"
                :label="item.phoneCode"
                :value="item.phoneCode"
              />
            </el-select>
            <el-input
              v-model="ruleForm.phoneNumber1"
              class="input-with-select"
              autosize
              type="textarea"
              resize="none"
              :disabled="onlyRead"
            />
          </el-form-item>
          <!-- 手机号2 -->
          <el-form-item :label="$t('entity.add_contact_phoneNumber2')" prop="phoneNumber2" class="phoneNumber2">
            <el-select
              v-model="ruleForm.phoneAreaCode2"
              :placeholder="$t('entity.add_contact_phoneNumber_areacode')"
              filterable
              :style="{ width: '160px', marginRight: '10px' }"
              :disabled="onlyRead"
            >
              <el-option
                v-for="item in areaCodeOptions.value"
                :key="item.id"
                :label="item.phoneCode"
                :value="item.phoneCode"
              />
            </el-select>
            <el-input
              v-model="ruleForm.phoneNumber2"
              class="input-with-select"
              autosize
              type="textarea"
              resize="none"
              :disabled="onlyRead"
            />
          </el-form-item>
        </div>
      </div>
      <div v-if="nowType && !onlyRead" class="btn">
        <el-form-item>
          <el-button @click="cancelForm()">{{ $t('entity.add_btn_cancel') }}</el-button>
          <el-button type="primary" @click="saveForm(ruleFormRef)">{{ $t('entity.add_btn_save') }}</el-button>
          <el-button type="primary" @click="confirmForm(ruleFormRef)">{{ $t('entity.add_btn_confirm') }}</el-button>
        </el-form-item>
      </div>
      <div v-if="!nowType" class="none">
        <img class="none_img" src="../../assets/img/entity/entityTypeNone.png" alt="" />
        <span>{{ $t('entity.add_none_tips') }}</span>
      </div>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, computed, watch } from 'vue';
import type { FormInstance } from 'element-plus';
import { useStore } from 'vuex';
import { useI18n } from 'vue-i18n';
import entityApi from '@/apis/entity';
import { getRequest } from '@/apis/request';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import router from '@/router';
import lodash from 'lodash';
// @ts-ignore
let { t } = useI18n();
const store = useStore();
const query = useRouter().currentRoute.value.query;

const isLawyer = store.state.user.roles.includes('legal');
const uid = store.state.user.info.id;
const locale = store.state.locale.key;
const activeTag = store.state.menu.activeTag;
const tagList = store.state.menu.tagList;
let countryOptions: any = ref([]);
let stateOptions: any = ref([]);
let cityOptions: any = ref([]);
let required = ref(false);
const isConfirm = ref(false);
const isSave = ref(false);
const onlyRead = computed(() => {
  return (!isLawyer && ruleForm.value.entityType === 108) || (!isLawyer && !!ruleForm.value.attorneyRegistrationNumber);
});
const entityTypeOptions = reactive([
  {
    value: 101,
    label: 'entity.add_general_entityType_supplier',
    disabled: false,
  },
  {
    value: 102,
    label: 'entity.add_general_entityType_franchised',
    disabled: false,
  },
  {
    value: 106,
    label: 'entity.add_general_entityType_granted',
    disabled: false,
  },
  {
    value: 104,
    label: 'entity.add_general_entityType_complainant',
    disabled: false,
  },
  {
    value: 105,
    label: 'entity.add_general_entityType_defendant',
    disabled: false,
  },
  {
    value: 107,
    label: 'entity.add_general_entityType_grantor',
    disabled: false,
  },
  {
    value: 103,
    label: 'entity.add_general_entityType_lawyer',
    disabled: false,
  },
  {
    value: 108,
    label: 'entity.add_general_entityType_groupCompany',
    disabled: !isLawyer,
  },
]);
const civilStatusOptions = reactive([
  {
    value: 201,
    label: 'entity.add_general_civilStatus_unique',
    disabled: false,
  },
  {
    value: 202,
    label: 'entity.add_general_civilStatus_married',
    disabled: false,
  },
  {
    value: 203,
    label: 'entity.add_general_civilStatus_widow',
    disabled: false,
  },
  {
    value: 204,
    label: 'entity.add_general_civilStatus_divorce',
    disabled: false,
  },
  {
    value: 205,
    label: 'entity.add_general_civilStatus_buried',
    disabled: false,
  },
  {
    value: 206,
    label: 'entity.add_general_civilStatus_other',
    disabled: false,
  },
]);
let areaCodeOptions = reactive({
  value: [
    {
      id: '86',
      phoneCode: '+86',
    },
  ],
});
const ruleFormRef = ref<FormInstance>();
const identity = ref(0);
const nationality = ref(0);

let ruleFormLB = reactive({
  value: {
    identity: identity,
    nationality: nationality,
    entityType: '',
    entityName: '',

    documentNumber: '',
    documentType: '',
    idCard: '',
    attorneyRegistrationNumber: '',
    profession: '',
    civilStatus: '',
    tradeName: '',
    stateRegistration: '',
    cityRegistration: '',
    isBaxiCep: false,
    zipCode: '',
    streetNumber: '',
    address: '',
    district: '',
    country: '',
    state: '',
    city: '',

    name: '',
    email: '',
    phoneNumber1: '',
    phoneNumber2: '',
    phoneAreaCode1: '',
    phoneAreaCode2: '',
  },
});
let ruleFormLF = reactive({
  value: {
    identity: identity,
    nationality: nationality,
    entityType: '',
    entityName: '',

    documentNumber: '',
    documentType: '',
    idCard: '',
    attorneyRegistrationNumber: '',
    profession: '',
    civilStatus: '',
    tradeName: '',
    stateRegistration: '',
    cityRegistration: '',

    isBaxiCep: false,
    zipCode: '',
    streetNumber: '',
    address: '',
    district: '',
    country: '',
    state: '',
    city: '',

    name: '',
    email: '',
    phoneNumber1: '',
    phoneNumber2: '',
    phoneAreaCode1: '',
    phoneAreaCode2: '',
  },
});
let ruleFormPB = reactive({
  value: {
    identity: identity,
    nationality: nationality,
    entityType: '',
    entityName: '',
    documentNumber: '',
    documentType: '',
    idCard: '',
    attorneyRegistrationNumber: '',
    profession: '',
    civilStatus: '',
    tradeName: '',
    stateRegistration: '',
    cityRegistration: '',
    isBaxiCep: false,
    zipCode: '',
    streetNumber: '',
    address: '',
    district: '',
    country: '',
    state: '',
    city: '',

    name: '',
    email: '',
    phoneNumber1: '',
    phoneNumber2: '',
    phoneAreaCode1: '',
    phoneAreaCode2: '',
  },
});
let ruleFormPF = reactive({
  value: {
    identity: identity,
    nationality: nationality,
    entityType: '',
    entityName: '',

    documentNumber: '',
    documentType: '',
    idCard: '',
    attorneyRegistrationNumber: '',
    profession: '',
    civilStatus: '',
    tradeName: '',
    stateRegistration: '',
    cityRegistration: '',
    isBaxiCep: false,
    zipCode: '',
    streetNumber: '',
    address: '',
    district: '',
    country: '',
    state: '',
    city: '',

    name: '',
    email: '',
    phoneNumber1: '',
    phoneNumber2: '',
    phoneAreaCode1: '',
    phoneAreaCode2: '',
  },
});
const temp = reactive({
  value: {
    identity: identity,
    nationality: nationality,
    entityType: '',

    documentNumber: '',
    documentType: '',
    idCard: '',
    attorneyRegistrationNumber: '',
    profession: '',
    civilStatus: '',
    tradeName: '',
    stateRegistration: '',
    cityRegistration: '',
    isBaxiCep: false,
    zipCode: '',
    streetNumber: '',
    address: '',
    district: '',
    country: '',
    state: '',
    city: '',

    name: '',
    email: '',
    phoneNumber1: '',
    phoneNumber2: '',
    phoneAreaCode1: '',
    phoneAreaCode2: '',
  },
});
const getViaCep = (zipCode: String) => {
  getRequest('https://viacep.com.br/ws/' + zipCode + '/json/', {}).then((res) => {
    if (!res.erro) {
      ruleForm.value.address = res.logradouro;
      ruleForm.value.district = res.bairro;
      ruleForm.value.streetNumber = res.complemento;
      ruleForm.value.country = 'Brasil';
      ruleForm.value.state = res.uf;
      ruleForm.value.city = res.localidade;
      ruleForm.value.isBaxiCep = true;
    } else {
      ruleForm.value.isBaxiCep = false;
    }
    getCSC();
  });
};
const init = () => {
  if (query.id) {
    entityApi.getEntityById({ id: query.id }).then((res) => {
      if (!!res && res.data && res.code === 200) {
        identity.value = res.data.entityItem.identity;
        nationality.value = res.data.entityItem.nationality;
        if (identity.value === 1) {
          if (nationality.value === 1) {
            ruleFormLB.value = res.data.entityItem;
            if (res.data.entityItem.zipCode.length === 8) {
              getViaCep(res.data.entityItem.zipCode);
            }
          } else if (nationality.value === 2) {
            ruleFormLF.value = res.data.entityItem;
            getCSC();
          }
        } else if (identity.value === 2) {
          if (nationality.value === 1) {
            ruleFormPB.value = res.data.entityItem;
            if (res.data.entityItem.zipCode.length === 8) {
              getViaCep(res.data.entityItem.zipCode);
            }
          } else if (nationality.value === 2) {
            ruleFormPF.value = res.data.entityItem;
            getCSC();
          }
        }
      }
    });
  } else {
    entityApi.getCountryList({ locale }).then((res) => {
      if (!!res && res.data && res.code === 200) {
        countryOptions.value = res.data;
      }
    });
  }
  entityApi.getAreaCodeList({ locale }).then((res) => {
    if (!!res && res.data && res.code === 200) {
      areaCodeOptions.value = res.data;
    }
  });
};
init();
const getCSC = () => {
  entityApi.getCountryList({ locale }).then((res) => {
    if (!!res && res.data && res.code === 200) {
      countryOptions.value = res.data;
      if (!ruleForm.value.isBaxiCep) {
        const country = countryOptions.value.find((item: any) => item.name.includes(ruleForm.value.country));
        entityApi.getStateList({ locale, countryId: country.id }).then((res) => {
          if (!!res && res.data && res.code === 200) {
            stateOptions.value = res.data;
            const state = stateOptions.value.find((item: any) => item.name.includes(ruleForm.value.state));
            entityApi.getCityList({ locale, statesId: state.id }).then((res) => {
              if (!!res && res.data && res.code === 200) {
                if (res.data.length) {
                  cityOptions.value = res.data;
                } else {
                  cityOptions.value = [
                    {
                      name: state.name,
                      id: state.id,
                    },
                  ];
                }
              }
            });
          }
        });
      }
    }
  });
};
const nowType = computed(() => {
  let res: any = null;
  if (ruleFormRef.value) {
    ruleFormRef.value.clearValidate();
  }
  if (identity.value === 1) {
    if (nationality.value === 1) {
      res = 'LB';
    } else if (nationality.value === 2) {
      res = 'LF';
    }
  } else if (identity.value === 2) {
    if (nationality.value === 1) {
      res = 'PB';
    } else if (nationality.value === 2) {
      res = 'PF';
    }
  }
  return res;
});
const ruleForm = computed(() => {
  let res: any = {};
  if (identity.value === 1) {
    if (nationality.value === 1) {
      res = ruleFormLB.value;
    } else if (nationality.value === 2) {
      res = ruleFormLF.value;
    } else {
      res = temp.value;
    }
  } else if (identity.value === 2) {
    if (nationality.value === 1) {
      res = ruleFormPB.value;
    } else if (nationality.value === 2) {
      res = ruleFormPF.value;
    } else {
      res = temp.value;
    }
  } else {
    res = temp.value;
  }
  return res;
});
const documentTypeOptions = computed(() => [
  {
    value: 301,
    label: 'entity.add_general_documentType_cnpj',
    disabled: !(nowType.value === 'LF' || nowType.value === 'LB'),
  },
  {
    value: 303,
    label: 'entity.add_general_documentType_cpf',
    disabled: !(nowType.value === 'PB'),
  },
  {
    value: 302,
    label: 'entity.add_general_documentType_nif',
    disabled: !(nowType.value === 'LF'),
  },
  {
    value: 304,
    label: 'entity.add_general_documentType_rne',
    disabled: !(nowType.value === 'PF'),
  },
  {
    value: 305,
    label: 'entity.add_general_documentType_rnm',
    disabled: !(nowType.value === 'PF'),
  },
]);
watch(
  [
    () => ruleForm.value.country,
    () => ruleForm.value.state,
    () => ruleForm.value.zipCode,
    () => ruleForm.value.documentNumber,
    () => nowType.value,
  ],
  (newValue, oldValue) => {
    if (!oldValue[0] && !oldValue[1] && !oldValue[2] && !oldValue[3] && !oldValue[4]) {
      return;
    } else if (
      newValue[0] !== oldValue[0] &&
      !ruleForm.value.isBaxiCep &&
      ruleForm.value.country &&
      newValue[4] === oldValue[4]
    ) {
      ruleForm.value.state = '';
      ruleForm.value.city = '';
      const country = countryOptions.value.find((item: any) => ruleForm.value.country === item.name);
      entityApi.getStateList({ locale, countryId: country.id }).then((res) => {
        if (!!res && res.data && res.code === 200) {
          stateOptions.value = res.data;
        }
      });
    } else if (
      newValue[1] !== oldValue[1] &&
      !ruleForm.value.isBaxiCep &&
      ruleForm.value.state &&
      newValue[4] === oldValue[4]
    ) {
      ruleForm.value.city = '';
      const state = stateOptions.value.find((item: any) => item.name.includes(ruleForm.value.state));
      entityApi.getCityList({ locale, statesId: state.id }).then((res) => {
        if (!!res && res.data && res.code === 200) {
          if (res.data.length) {
            cityOptions.value = res.data;
          } else {
            cityOptions.value = [
              {
                name: state.name,
                id: state.id,
              },
            ];
          }
        }
      });
    } else if (
      newValue[2] !== oldValue[2] &&
      (nowType.value === 'LB' || nowType.value === 'PB') &&
      newValue[2].length === 8 &&
      /^[0-9]{8}$/.test(newValue[2])
    ) {
      getViaCep(newValue[2]);
    } else if (
      newValue[2] !== oldValue[2] &&
      (nowType.value === 'LB' || nowType.value === 'PB') &&
      newValue[2].length !== 8 &&
      ruleForm.value.isBaxiCep
    ) {
      ruleForm.value.address = '';
      ruleForm.value.district = '';
      ruleForm.value.streetNumber = '';
      ruleForm.value.country = '';
      ruleForm.value.state = '';
      ruleForm.value.city = '';
      ruleForm.value.isBaxiCep = false;
    }
    if (newValue[4] !== oldValue[4]) {
      required.value = false;
    }
  },
  { deep: true, immediate: true },
);
let tipsMandatory = computed(() => t('entity.add_tips_mandatory'));
let tipsFormat = computed(() => t('entity.add_tips_format'));
let tipsUniqueness = computed(() => t('entity.add_tips_uniqueness'));
const rules = computed(() => {
  return {
    // basic
    identity: [{ required: required.value, message: '' }],
    nationality: [{ required: required.value, message: '' }],
    // general
    entityType: [{ required: required.value, validator: validate, trigger: 'change' }],
    entityName: [{ required: required.value, validator: entityNameValidate, trigger: 'change' }],
    document: [{ required: required.value, validator: validateDocument, trigger: 'change' }],
    // address
    zipCode: [{ required: required.value, validator: validateCep, trigger: 'change' }],
    streetNumber: [{ required: required.value, validator: validate, trigger: 'change' }],
    address: [{ required: required.value, validator: validate, trigger: 'change' }],
    district: [{ required: required.value, validator: validate, trigger: 'change' }],
    countryStateCity: [{ required: required.value, validator: validateCountryStateCity, trigger: 'change' }],
    // concat
    email: [{ required: false, validator: validateEmail, trigger: ['blur', 'change'] }],
    tipsMandatory: t('entity.add_tips_mandatory'),
    tipsFormat: t('entity.add_tips_format'),
    tipsUniqueness: t('entity.add_tips_uniqueness'),
  };
});
const entityNameValidate = (rule: any, value: any, callback: any) => {
  if (!value && (isConfirm.value || isSave.value)) {
    callback(new Error(tipsMandatory.value));
  } else {
    callback();
  }
};
const validate = (rule: any, value: any, callback: any) => {
  if (!value && (isConfirm.value || required.value)) {
    callback(new Error(tipsMandatory.value));
  } else {
    callback();
  }
};
const validateEmail = (rule: any, value: any, callback: any) => {
  if ((!value || value === '') && (isConfirm.value || isSave.value)) {
    callback();
  } else if (
    !/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value) &&
    (isConfirm.value || isSave.value)
  ) {
    callback(new Error(tipsFormat.value));
  } else {
    callback();
  }
};
const validateCep = (rule: any, value: any, callback: any) => {
  if (!value && required.value) {
    callback(new Error(tipsMandatory.value));
  } else if (
    !/^[0-9]{8}$/.test(value) &&
    value &&
    (nowType.value === 'PB' || nowType.value === 'LB') &&
    (isConfirm.value || isSave.value)
  ) {
    callback(new Error(tipsFormat.value));
  } else {
    callback();
  }
};
const validateDocument = (rule: any, value: any, callback: any) => {
  if ((!ruleForm.value.documentType || !ruleForm.value.documentNumber) && required.value) {
    callback(new Error(tipsMandatory.value));
  } else if (
    ruleForm.value.documentType === 301 &&
    ruleForm.value.documentNumber &&
    (isSave.value || isConfirm.value)
  ) {
    entityApi.verifyCNPJ({ cnpj: ruleForm.value.documentNumber }).then((res) => {
      if (res.data) {
        entityApi.verifyUniqueness({ docNum: ruleForm.value.documentNumber, id: query.id }).then((res) => {
          if (res.data) {
            callback();
          } else {
            callback(new Error(tipsUniqueness.value));
          }
        });
      } else {
        callback(new Error(tipsFormat.value));
      }
    });
  } else if (
    ruleForm.value.documentType === 303 &&
    ruleForm.value.documentNumber &&
    (isSave.value || isConfirm.value)
  ) {
    entityApi.verifyCPF({ cpf: ruleForm.value.documentNumber }).then((res) => {
      if (res.data) {
        entityApi.verifyUniqueness({ docNum: ruleForm.value.documentNumber, id: query.id }).then((res) => {
          if (res.data) {
            callback();
          } else {
            callback(new Error(tipsUniqueness.value));
          }
        });
      } else {
        callback(new Error(tipsFormat.value));
      }
    });
  } else if (ruleForm.value.documentType && ruleForm.value.documentNumber && (isSave.value || isConfirm.value)) {
    entityApi.verifyUniqueness({ docNum: ruleForm.value.documentNumber, id: query.id }).then((res) => {
      if (res.data) {
        callback();
      } else {
        callback(new Error(tipsUniqueness.value));
      }
    });
  } else {
    callback();
  }
};
const validateCountryStateCity = (rule: any, value: any, callback: any) => {
  if ((!ruleForm.value.country || !ruleForm.value.state || !ruleForm.value.city) && required.value) {
    callback(new Error(tipsMandatory.value));
  } else {
    callback();
  }
};
const saveForm = lodash.debounce(async (formEl: FormInstance | undefined) => {
  required.value = false;
  isSave.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    isSave.value = false;
    if (valid) {
      console.log('save!');
      entityApi.saveEntity({ ...ruleForm.value, uid }).then((res) => {
        if (res.data) {
          router.push('/entityList');
          closePage();
          ElMessage({
            message: res.msg,
            type: 'success',
          });
        }
        if (res.code === 5020) {
          router.push('/entityList');
          closePage();
        }
      });
    } else {
      // @ts-ignore
      ElMessageBox.alert(t('entity.add_tips_save_fail'), {
        type: 'warning',
        confirmButtonText: t('entity.add_tips_save_fail_btn'),
      });
      console.log('error Save!', fields);
    }
  });
}, 500);
const confirmForm = lodash.debounce(async (formEl: FormInstance | undefined) => {
  required.value = true;
  isConfirm.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    isConfirm.value = false;
    if (valid) {
      console.log('submit!');
      entityApi.confirmeEntity({ ...ruleForm.value, uid }).then((res) => {
        if (res.data) {
          router.push('/entityList');
          closePage();
          ElMessage({
            message: res.msg,
            type: 'success',
          });
        }
        if (res.code === 5020) {
          router.push('/entityList');
          closePage();
        }
      });
    } else {
      ElMessageBox.alert(t('entity.add_tips_confirm_fail'), {
        type: 'warning',
      });
      console.log('error submit!', fields);
    }
  });
}, 500);

const cancelForm = () => {
  router.go(-1);
};
const closePage = () => {
  const newTagList = tagList.filter((a: any) => a.name !== activeTag);
  store.commit('setTagList', newTagList);
  store.commit('removeCacheRoute', [activeTag]);
};
const iconClosePage = () => {
  router.go(-1);
};
</script>

<style lang="scss" scoped>
h3,
h5 {
  font-size: 18px;
}
.container {
  background-color: white;
  border-radius: 10px;
  padding: 20px 24px;
  min-height: calc(100vh - 120px);
  &_titleBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 20px;
    box-shadow: inset 0 -1px 0 0 #edf1ef;
    margin-bottom: 20px;
  }
  .basic {
    display: flex;
    width: 100%;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;
    width: 90%;
    margin: auto;
    justify-content: space-between;
    :deep(.common) {
      .el-form-item__label::after {
        content: '*';
        color: red;
        margin-left: 4px;
      }
    }
    .document,
    .phoneNumber1,
    .phoneNumber2 {
      :deep(.el-form-item__content) {
        flex-wrap: nowrap;
        align-items: flex-start;
      }
    }
    .el-radio {
      margin-right: 10px;
    }
  }
  .none {
    margin: 50px auto;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    &_img {
      width: 200px;
      height: 120px;
    }
    span {
      width: 100%;
      text-align: center;
    }
  }
  .general,
  .address,
  .contact {
    width: 100%;
  }
  .general_content,
  .address_content,
  .contact_content {
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
      flex: 0 1 28%;
    }
    .csc {
      flex: auto;
      .el-select {
        flex: 0 1 17%;
        margin-right: 10px;
      }
    }
  }
  .general_title,
  .address_title,
  .contact_title {
    display: flex;
    align-items: center;
    &::before {
      content: '';
      display: block;
      width: 4px;
      height: 19px;
      background-color: #419b62;
      margin-right: 10px;
    }
  }
  .btn {
    width: 100%;
    display: flex;
    justify-content: center;
  }
}
</style>
